package com.clound.order.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * Created by zzy on 2018/4/21.
 */
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {

    /**
     * 服务降级
     * @return
     */
    //@HystrixCommand(fallbackMethod = "fallback")
/*    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })*///超时时间设置为3秒
/*    @HystrixCommand(commandProperties = {
//        this.circuitBreakerEnabled = getProperty(propertyPrefix, key, "circuitBreaker.enabled", builder.getCircuitBreakerEnabled(), default_circuitBreakerEnabled);
//      this.circuitBreakerRequestVolumeThreshold = getProperty(propertyPrefix, key, "circuitBreaker.requestVolumeThreshold", builder.getCircuitBreakerRequestVolumeThreshold(), default_circuitBreakerRequestVolumeThreshold);
//   this.circuitBreakerSleepWindowInMilliseconds = getProperty(propertyPrefix, key, "circuitBreaker.sleepWindowInMilliseconds", builder.getCircuitBreakerSleepWindowInMilliseconds(), default_circuitBreakerSleepWindowInMilliseconds);
//  this.circuitBreakerErrorThresholdPercentage = getProperty(propertyPrefix, key, "circuitBreaker.errorThresholdPercentage", builder.getCircuitBreakerErrorThresholdPercentage(), default_circuitBreakerErrorThresholdPercentage);

    @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//设置熔断
    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//断路器的最小请求数
    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口，及断路器打开时时间倒计时
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")//错误比例


    })*///服务熔断 当错误率达到一定程度的时候，就自动降级
    @HystrixCommand(commandKey = "getProductInfoList")
    @GetMapping(value = "/getHystrixTest")
    public String getProductInfoList(){
        RestTemplate restTemplate=new RestTemplate();
        String result= restTemplate.postForObject("http://localhost:8080/product/listForOrder",
                Arrays.asList("12312"),String.class);
        return result;
    }

    private String fallback(){
        return "请稍后再试";
    }

    private String defaultFallback(){
        return "默认fallback";
    }
}
